package keenabc

import (
	"os"
	"strings"
	"github.com/astaxie/beego"
	"fmt"
	"database/sql"
	"io/ioutil"
)

type TableStruct struct {
	ColumnName       	string
	DataType	   		string
}

func GenerateModel(moduleName string, TableName string, ColumnNames []string, columnTypes []string) bool {

	var connstr string
	connstr = fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8",
		beego.AppConfig.String("user"),
		beego.AppConfig.String("password"),
		beego.AppConfig.String("host"),
		beego.AppConfig.String("port"),
		beego.AppConfig.String("db"))

	db, err := sql.Open("mysql", connstr)
	if err != nil {
		fmt.Println(err)
	}


	//建表
	var strsql string

	strsql = "CREATE TABLE "+ TableName +" ("

	for i := 0; i < len(ColumnNames); i++ {
		if i != len(ColumnNames) -1 {
			strsql += ColumnNames[i] + " " + columnTypes[i] + ", "
		} else {
			strsql += ColumnNames[i] + " " + columnTypes[i]
		}
	}

	strsql += ");"

	rows,err := db.Query(strsql)

	if err != nil {
		fmt.Println(err)
	} else {
		fmt.Println(rows)
	}

	path, _ := os.Getwd()
	//fmt.Println(path)
	FileName := moduleName

	//Create Model
	model, _ := os.OpenFile(path+"/models/"+ FileName + ".go" , os.O_CREATE|os.O_RDWR, 0766)

	var modelstr string

	for i := 0; i < len(ColumnNames); i++ {
		var temp string
		kv := strings.SplitN(columnTypes[i], "(", 2)
		switch kv[0] {
		case "varchar" :
			temp = "string"
		case "int" :
			temp = "int"
		}
		modelstr += NameChange(ColumnNames[i]) + " " + temp + " `orm:\"column("+ ColumnNames[i] +");\"`\n"
	}

	modelTpl = strings.Replace(modelTpl, "{{StructName}}", FileName, -1)
	modelTpl = strings.Replace(modelTpl, "{{StructContent}}", modelstr, -1)
	modelTpl = strings.Replace(modelTpl, "{{TableName}}", TableName, -1)
	modelTpl = strings.Replace(modelTpl, "{{structname}}", strings.ToLower(FileName), -1)

	model.WriteString(modelTpl)

	var fileContent string

	content, err := ioutil.ReadFile(path+"/models/Init.go")
	router, _ := os.OpenFile(path+"/models/Init.go" , os.O_CREATE|os.O_RDWR, 0766)

	lines := strings.Split(string(content), "\n")
	for _, v := range lines {
		fileContent += v + "\n"
		if strings.Contains(v, "//RegisterModel-begin") {
			fileContent += "orm.RegisterModel(new("+ FileName +"))\n"
		}

	}

	router.WriteString(fileContent)

	GoFmt(path+"/models/"+ FileName + ".go")

	return true
}